/**
 * Copyright 2010, Lars J. Nilsson <http://www.larsan.net> 
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package net.larsan.dconf.jbc;

import net.larsan.dconf.DPath;
import net.larsan.dconf.util.DPaths;

public class PathNormalizer {
	
	public static final String ROOT_DOMAIN = "root";
	public static final String ROOT = "/" + ROOT_DOMAIN;
	public static final String DOMAINS = "/domain";
	
	public String toJbc(DPath path) {
		return toJbcFromString(path.getFullPath());
	}

	public String toJbcFromString(String path) {
		int i = path.indexOf(':');
		if(i == -1) {
			return append(ROOT, path);
		} else {
			String domain = path.substring(0, i);
			path = path.substring(i + 1, path.length());
			if(domain.equals(ROOT_DOMAIN)) {
				return toJbcFromString(path);
			} else {
				return append(append(DOMAINS, domain), path);
			}
		}
	}

	public String fromJbcToString(String path) {
		if(path.startsWith(ROOT)) {
			path = path.substring(ROOT.length());
			return ROOT_DOMAIN + ":" + verifyFirstSlash(path);
		} else if(path.startsWith(DOMAINS)) {
			path = path.substring(DOMAINS.length());
			if(path.startsWith("/")) {
				path = path.substring(1);
			}
			int i = path.indexOf('/');
			String domain = (i == -1 ? path : path.substring(0, i));
			if(domain.length() == 0) {
				return fromJbcToString(ROOT);
			}
			path = (i == -1 ? "" : path.substring(i + 1));
			return domain + ":" + verifyFirstSlash(path);
		} else {
			return ROOT_DOMAIN + ":" + verifyFirstSlash(path);
		}
	}
	
	public DPath fromJbc(String path) {
		return DPaths.safeParse(fromJbcToString(path));
	}
	

	// --- PRIVATE METHODS --- //
	
	private String verifyFirstSlash(String path) {
		return (path.startsWith("/") ? path : "/" + path);
	}
	
	private String append(String p1, String p2) {
		if(p1.endsWith("/")) {
			if(p2.startsWith("/")) {
				return p1 + p2.substring(1); 
			} else {
				return p1 + p2;
			}
		} else {
			if(p2.startsWith("/")) {
				return p1 + p2;
			} else {
				return p1 + "/" + p2;
			}
		}
	}
}
